home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 5492 < prev    next >
Encoding:
Text File  |  1996-08-05  |  39.7 KB  |  972 lines

  1. Path: news.wyoming.com!usenet
  2. From: dcromley@wyoming.com (RePost)
  3. Newsgroups: comp.lang.c++
  4. Subject: C++ FAQ:  re-posting #2/4
  5. Date: 5 Feb 1996 00:04:15 GMT
  6. Organization: wyoming.com LLC
  7. Message-ID: <4f3hhv$a96@horn.wyoming.com>
  8. NNTP-Posting-Host: cys-cap-6.wyoming.com
  9. Mime-Version: 1.0
  10. X-Newsreader: WinVN 0.99.2
  11.  
  12. (reposted from M. Cline to get them together)
  13. Summary: Please read this before posting to comp.lang.c++
  14.  
  15. comp.lang.c++ Frequently Asked Questions list (with answers, fortunately).
  16. Copyright (C) 1991-96 Marshall P. Cline, Ph.D.
  17. Posting 2 of 4.
  18. Posting #1 explains copying permissions, (no)warranty, table-of-contents, etc
  19.  
  20. ==============================================================================
  21. SECTION 9: Freestore management
  22. ==============================================================================
  23.  
  24. Q33: Does "delete p" delete the pointer "p", or the pointed-to-data, "*p"?
  25.  
  26. The pointed-to-data.
  27.  
  28. "delete" really means "delete the thing pointed to by."  The same abuse of
  29. English occurs when "free"ing the memory pointed to by a ptr in C ("free(p)"
  30. really means "free_the_stuff_pointed_to_by(p)").
  31.  
  32. ==============================================================================
  33.  
  34. Q34: Can I "free()" pointers allocated with "new"?  Can I "delete" pointers
  35.    alloc'd with "malloc()"?
  36.  
  37. No.
  38.  
  39. It is perfectly legal, moral, and wholesome to use malloc/free and new/delete
  40. in the same program, but it is illegal, immoral, and despicable to free a
  41. pointer allocated via new, or to delete a pointer allocated via malloc.
  42.  
  43. ==============================================================================
  44.  
  45. Q35: Why should I use "new" instead of trustworthy old malloc()?
  46.  
  47. Constructors/destructors, type safety, overridability.
  48.  
  49. Constructors/destructors: unlike "malloc(sizeof(Fred))", "new Fred()" calls
  50. Fred's constructor.  Similarly, "delete p" calls "*p"'s destructor.
  51.  
  52. Type safety: malloc() returns a "void*" which isn't type safe.  "new Fred()"
  53. returns a ptr of the right type (a "Fred*").
  54.  
  55. Overridability: "new" is an operator that can be overridden by a class, while
  56. "malloc" is not overridable on a per-class basis.
  57.  
  58. ==============================================================================
  59.  
  60. Q36: Why doesn't C++ have a "realloc()" along with "new" and "delete"?
  61.  
  62. To save you from disaster.
  63.  
  64. When realloc() has to copy the allocation, it uses a BITWISE copy operation,
  65. which will tear most C++ objects to shreds.  C++ objects should be allowed to
  66. copy themselves: they use their own copy constructor or assignment operator.
  67.  
  68. ==============================================================================
  69.  
  70. Q37: How do I allocate / unallocate an array of things?
  71.  
  72. Use new[] and delete[]:
  73.  
  74.         Fred* p = new Fred[100];
  75.         //...
  76.         delete [] p;
  77.  
  78. Any time you use the "[...]" in the "new" expression, you *!*MUST*!* use "[]"
  79. in the "delete" statement.  This syntax is necessary because there is no
  80. syntactic difference between a pointer to a thing and a pointer to an array of
  81. things (something we inherited from C).
  82.  
  83. ==============================================================================
  84.  
  85. Q38: What if I forget the "[]" when "delete"ing array allocated via "new
  86.    Fred[n]"?
  87.  
  88. All life comes to a catastrophic end.
  89.  
  90. It is the programmer's --not the compiler's-- responsibility to get the
  91. connection between new[] and delete[] correct.  If you get it wrong, neither a
  92. compile-time nor a run-time error message will be generated by the compiler.
  93. Heap corruption is a likely result.  Or worse.  Your program will probably die.
  94.  
  95. ==============================================================================
  96.  
  97. Q39: Is it legal (and moral) for a member function to say "delete this"?
  98.  
  99. As long as you're careful, you'll be ok.
  100.  
  101. Here's how I define "careful":
  102. 1) You're absolutely 100% positive sure that "this" was allocated via "new"
  103.    (not by "new[]", nor by placement "new", by by plain ordinary "new").
  104. 2) You're absolutely 100% positive sure that your member function will be
  105.    the last member function invoked on this object.
  106. 3) After you do the suicide thing ("delete this;"), you must not touch any
  107.    piece of "this" object, including data or methods.
  108. 4) After you do the suicide thing ("delete this;"), you must not touch the
  109.    "this" pointer.  In other words, you must not examine it, compare it with
  110.    another pointer or with NULL, print it, cast it, do anything with it.
  111.  
  112. Naturally the usual caveats apply in cases where your "this" pointer is a
  113. pointer to a base class and the destructor isn't virtual.
  114.  
  115. ==============================================================================
  116.  
  117. Q40: How do I allocate multidimensional arrays using new?
  118.  
  119. There are many ways to do this, depending on how flexible you want the array
  120. sizing to be.  On one extreme, if you know all the dimensions at compile-time,
  121. you can allocate multidimensional arrays statically (as in C):
  122.  
  123.         class Fred { /*...*/ };
  124.  
  125.         void manipulateArray()
  126.         {
  127.           Fred matrix[10][20];
  128.  
  129.           //use matrix[i][j]...
  130.  
  131.           //no need for explicit deallocation
  132.         }
  133.  
  134. On the other extreme, if you want to allow the various slices of the matrix to
  135. have a different sizes, you can allocate everything off the freestore:
  136.  
  137.         void manipulateArray(unsigned nrows, unsigned ncols[])
  138.         //'nrows' is the number of rows in the array.
  139.         //therefore valid row numbers are from 0 to nrows-1 inclusive.
  140.         //'ncols[r]' is the number of columns in row 'r' ('r' in [0..nrows-1]).
  141.         {
  142.           Fred** matrix = new Fred*[nrows];
  143.           for (unsigned r = 0; r < nrows; ++r)
  144.             matrix[r] = new Fred[ ncols[r] ];
  145.  
  146.           //use matrix[i][j]...
  147.  
  148.           //deletion is the opposite of allocation:
  149.           for (r = nrows; r > 0; --r)
  150.             delete [] matrix[r-1];
  151.           delete [] matrix;
  152.         }
  153.  
  154. ==============================================================================
  155.  
  156. Q41: Does C++ have arrays whose length can be specified at run-time?
  157.  
  158. Yes, in the sense that STL has a vector template that provides this behavior.
  159. See on "STL" in the "Libraries" section.
  160.  
  161. No, in the sense that built-in array types need to have their length specified
  162. at compile time.
  163.  
  164. Yes, in the sense that even built-in array types can specify the first index
  165. bounds at run-time.  E.g., comparing with the previous FAQ, if you only need
  166. the first array dimension to vary, then you can just ask new for an array of
  167. arrays (rather than an array of pointers to arrays):
  168.  
  169.         const unsigned ncols = 100;
  170.         //'ncols' is not a run-time variable (number of columns in the array)
  171.  
  172.         class Fred { ... };
  173.  
  174.         void manipulateArray(unsigned nrows)
  175.         //'nrows' is a run-time variable (number of rows in the array)
  176.         {
  177.           Fred (*matrix)[ncols] = new Fred[nrows][ncols];
  178.  
  179.           //use matrix[i][j]
  180.  
  181.           //deletion is the opposite of allocation:
  182.           delete [] matrix;
  183.         }
  184.  
  185. You can't do this if you need anything other than the first dimension
  186. of the array to change at run-time.
  187.  
  188. ==============================================================================
  189.  
  190. Q42: How can I ensure objects of my class are always created via "new" rather
  191.    than as locals or global/static objects?
  192.  
  193. Make sure the class's constructors are "private:", and define "friend" or
  194. "static" fns that return a ptr to the objects created via "new" (make the
  195. constructors "protected:" if you want to allow derived classes).
  196.  
  197.         class Fred {    //only want to allow dynamicly allocated Fred's
  198.         public:
  199.           static Fred* create()                 { return new Fred();     }
  200.           static Fred* create(int i)            { return new Fred(i);    }
  201.           static Fred* create(const Fred& fred) { return new Fred(fred); }
  202.         private:
  203.           Fred();
  204.           Fred(int i);
  205.           Fred(const Fred& fred);
  206.           virtual ~Fred();
  207.         };
  208.  
  209.         main()
  210.         {
  211.           Fred* p = Fred::create(5);
  212.           ...
  213.           delete p;
  214.         }
  215.  
  216. ==============================================================================
  217. SECTION 10: Debugging and error handling
  218. ==============================================================================
  219.  
  220. Q43: How can I handle a constructor that fails?
  221.  
  222. Throw an exception.
  223.  
  224. Constructors don't have a return type, so it's not possible to use error codes.
  225. The best way to signal constructor failure is therefore to throw an exception.
  226.  
  227. Before C++ had exceptions, we signaled constructor failure by putting the
  228. object into a "half baked" state (e.g., by setting an internal status bit).
  229. There was a query ("inspector") method to check this bit, that allowed clients
  230. to discover whether they had a live object.  Other member functions would also
  231. check this bit, and, if the object wasn't really alive, do a no-op (or perhaps
  232. something more obnoxious such as "abort()").  This was really ugly.
  233.  
  234. ==============================================================================
  235.  
  236. Q44: How should I handle resources if my constructors may throw exceptions?
  237.  
  238. Every data member inside your object should clean up its own mess.
  239.  
  240. If a constructor throws an exception, the object's destructor is NOT run.  If
  241. your object has already done something that needs to be undone (such as
  242. allocating some memory, opening a file, or locking a semaphore), this "stuff
  243. that needs to be undone" MUST be remembered by a data member inside the object.
  244.  
  245. For example, rather than allocating memory into a raw "Fred*" data member, put
  246. the allocated memory into a "smart pointer" member object, and the destructor
  247. of this smart pointer will delete the Fred object when the smart pointer dies.
  248.  
  249. ==============================================================================
  250. SECTION 11: Const correctness
  251. ==============================================================================
  252.  
  253. Q45: What is "const correctness"?
  254.  
  255. A good thing.
  256.  
  257. Const correctness uses the keyword "const" to ensure const objects don't get
  258. mutated.  E.g., if function "f()" accepts a "String", and "f()" wants to
  259. promise not to change the "String", you:
  260.  
  261.  * can either pass by value:    void  f(      String  s   )  { /*...*/ }
  262.  * or by constant reference:    void  f(const String& s   )  { /*...*/ }
  263.  * or by constant pointer:      void  f(const String* sptr)  { /*...*/ }
  264.  * but NOT by non-const ref:    void  f(      String& s   )  { /*...*/ }
  265.  * NOR by non-const pointer:    void  f(      String* sptr)  { /*...*/ }
  266.  
  267. Attempted changes to "s" within a fn that takes a "const String&" are flagged
  268. as compile-time errors; neither run-time space nor speed is degraded.
  269.  
  270. Declaring the "constness" of a parameter is just another form of type safety.
  271. It is almost as if a constant String, for example, "lost" its various mutative
  272. operations.  If you find type safety helps you get systems correct (it does;
  273. especially in large systems), you'll find const correctness helps also.
  274.  
  275. ==============================================================================
  276.  
  277. Q46: Should I try to get things const correct "sooner" or "later"?
  278.  
  279. At the very, very, VERY beginning.
  280.  
  281. Back-patching const correctness results in a snowball effect: every "const" you
  282. add "over here" requires four more to be added "over there."
  283.  
  284. ==============================================================================
  285.  
  286. Q47: What is a "const member function"?
  287.  
  288. A member function that inspects (rather than mutates) its object.
  289.  
  290.         class Fred {
  291.         public:
  292.           void f() const;
  293.         };      // ^^^^^--- this implies "fred.f()" won't change "fred"
  294.  
  295. This means that the ABSTRACT (client-visible) state of the object isn't going
  296. to change (as opposed to promising that the "raw bits of the object's struct
  297. aren't going to change).  C++ compilers aren't allowed to take the "bitwise"
  298. interpretation, since a non-const alias could exist which could modify the
  299. state of the object (gluing a "const" ptr to an object doesn't promise the
  300. object won't change; it promises only that the object won't change VIA THAT
  301. POINTER).
  302.  
  303. "const" member functions are often called "inspectors."  Non-"const" member
  304. functions are often called "mutators."
  305.  
  306. ==============================================================================
  307.  
  308. Q48: What do I do if I want to update an "invisible" data member inside a
  309.    "const" member function?
  310.  
  311. Use "mutable", or use "const_cast".
  312.  
  313. A small percentage of inspectors need to make innocuous changes to data members
  314. (e.g., a "Set" object might want to cache its last lookup in hopes of improving
  315. the performance of its next lookup).  By saying the changes are "inocuous," I
  316. mean that the changes wouldn't be visible from outside the object's interface
  317. (otherwise the method would be a mutator rather than an inspector).
  318.  
  319. When this happens, the data member which will be modified should be marked as
  320. "mutable" (put the "mutable" keyword just before the data member's declaration;
  321. i.e., in the same place where you could put "const").  This tells the compiler
  322. that the data member is allowed to change during a const member function.  If
  323. you can't use "mutable", you can cast away the constness of "this" via
  324. "const_cast".  E.g., in "Set::lookup() const", you might say,
  325.  
  326.         Set* self = const_cast<Set*>(this);
  327.  
  328. After this line, "self" will have the same bits as "this" (e.g., "self==this"),
  329. but "self" is a "Set*" rather than a "const Set*".  Therefore you can use
  330. "self" to modify the object pointed to by "this".
  331.  
  332. ==============================================================================
  333.  
  334. Q49: Does "const_cast" mean lost optimization opportunities?
  335.  
  336. In theory, yes; in practice, no.
  337.  
  338. Even if a compiler outlawed "const_cast", the only way to avoid flushing the
  339. register cache across a "const" member function call would be to ensure that
  340. there are no non-const pointers that alias the object.  This can happen only in
  341. rare cases (when the object is constructed in the scope of the const member fn
  342. invocation, and when all the non-const member function invocations between the
  343. object's construction and the const member fn invocation are statically bound,
  344. and when every one of these invocations is also "inline"d, and when the
  345. constructor itself is "inline"d, and when any member fns the constructor calls
  346. are inline).
  347.  
  348. ==============================================================================
  349. SECTION 12: Inheritance
  350. ==============================================================================
  351.  
  352. Q50: Is inheritance important to C++?
  353.  
  354. Yep.
  355.  
  356. Inheritance is what separates abstract data type (ADT) programming from OOP.
  357.  
  358. ==============================================================================
  359.  
  360. Q51: When would I use inheritance?
  361.  
  362. As a specification device.
  363.  
  364. Human beings abstract things on two dimensions: part-of and kind-of.  A Ford
  365. Taurus is-a-kind-of-a Car, and a Ford Taurus has-a Engine, Tires, etc.  The
  366. part-of hierarchy has been a part of software since the ADT style became
  367. relevant; inheritance adds "the other" major dimension of decomposition.
  368.  
  369. ==============================================================================
  370.  
  371. Q52: How do you express inheritance in C++?
  372.  
  373. By the ": public" syntax:
  374.  
  375.         class Car : public Vehicle {
  376.                 //^^^^^^^^---- ": public" is pronounced "is-a-kind-of-a'
  377.           //...
  378.         };
  379.  
  380. We state the above relationship in several ways:
  381.  * Car is "a kind of a" Vehicle
  382.  * Car is "derived from" Vehicle
  383.  * Car is "a specialized" Vehicle
  384.  * Car is the "subclass" of Vehicle
  385.  * Vehicle is the "base class" of Car
  386.  * Vehicle is the "superclass" of Car (this not as common in the C++ community)
  387.  
  388. ==============================================================================
  389.  
  390. Q53: Is it ok to convert a pointer from a derived class to its base class?
  391.  
  392. Yes.
  393.  
  394. A derived class is a specialized version of the base class ("Derived is a
  395. kind-of Base").  The upward conversion is perfectly safe, and happens all the
  396. time (if I am pointing at a car, I am in fact pointing at a vehicle):
  397.  
  398.         void f(Vehicle* v);
  399.         void g(Car* c) { f(c); }        //perfectly safe; no cast
  400.  
  401. Note that the answer to this FAQ assumes we're talking about "public"
  402. inheritance; see below on "private/protected" inheritance for "the other kind".
  403.  
  404. ==============================================================================
  405.  
  406. Q54: Derived* --> Base* works ok; why doesn't Derived** --> Base** work?
  407.  
  408. C++ allows a Derived* to be converted to a Base*, since a Derived object is a
  409. kind of a Base object.  However trying to convert a Derived** to a Base** is
  410. (correctly) flagged as an error (if it was allowed, the Base** could be
  411. dereferenced (yielding a Base*), and the Base* could be made to point to an
  412. object of a DIFFERENT derived class.  This would be an error.
  413.  
  414. As a corollary, an array of Deriveds is-NOT-a-kind-of array of Bases.  At
  415. Paradigm Shift, Inc. we use the following example in our C++ training sessions:
  416.  
  417.                "A bag of apples is NOT a bag of fruit".
  418.  
  419. If a bag of apples COULD be passed as a bag of fruit, someone could put a
  420. banana into the bag of apples!
  421.  
  422. ==============================================================================
  423.  
  424. Q55: Does array-of-Derived is-NOT-a-kind-of array-of-Base mean arrays are
  425.    bad?
  426.  
  427. Yes, "arrays are evil" (jest kidd'n :-).
  428.  
  429. There's a very subtle problem with using raw built-in arrays.  Consider this:
  430.  
  431.         void f(Base* arrayOfBase)
  432.         {
  433.           arrayOfBase[3].memberfn();
  434.         }
  435.  
  436.         main()
  437.         {
  438.           Derived arrayOfDerived[10];
  439.           f(arrayOfDerived);
  440.         }
  441.  
  442. The compiler thinks this is perfectly type-safe, since it can convert a
  443. Derived* to a Base*.  But in reality it is horrendously evil: since Derived
  444. might be larger than Base, the array index in f() not only isn't type safe, it
  445. may not even be pointing at a real object!  In general it'll be pointing
  446. somewhere into the innards of some poor Derived.
  447.  
  448. The root problem is that C++ can't distinguish between a ptr-to-a-thing and a
  449. ptr-to-an-array-of-things.  Naturally C++ "inherited" this feature from C.
  450.  
  451. NOTE: if we had used an array-like CLASS instead of using a raw array (e.g., an
  452. "Array<T>" rather than a "T[]"), this problem would have been properly trapped
  453. as an error at compile time rather than at run-time.
  454.  
  455. ==============================================================================
  456. SUBSECTION 12A: Inheritance -- Virtual functions
  457. ==============================================================================
  458.  
  459. Q56: What is a "virtual member function"?
  460.  
  461. A virtual function allows derived classes to replace the implementation
  462. provided by the base class.  The compiler ensures the replacement is always
  463. called whenever the object in question is actually of the derived class, even
  464. if the object is accessed by a base pointer rather than a derived pointer.
  465. This allows algorithms in the base class to be replaced in the derived class,
  466. even if users don't know about the derived class.
  467.  
  468. Note: the derived class can partially replace ("override") the base class
  469. method (the derived class method can invoke the base class version if desired).
  470.  
  471. ==============================================================================
  472.  
  473. Q57: How can C++ achieve dynamic binding yet also static typing?
  474.  
  475. In the following discussion, "ptr" means either a pointer or a reference.
  476.  
  477. When you have a ptr, there are two types: the (static) type of the ptr, and the
  478. (dynamic) type of the pointed-to object (the object may actually be of a class
  479. that is derived from the class of the ptr).
  480.  
  481. "Static typing" means that the "legality" of the call is checked based on the
  482. static type of the ptr: if the type of the ptr can handle the member fn,
  483. certainly the pointed-to object can handle it as well.
  484.  
  485. "Dynamic binding" means that the "code" that is called is based on the dynamic
  486. type of the pointed-to object.  This is called "dynamic binding," since the
  487. actual code being called is determined dynamically (at run time).
  488.  
  489. ==============================================================================
  490.  
  491. Q58: Should a derived class replace ("override") a non-virtual fn from a base
  492.    class?
  493.  
  494. It's legal, but it ain't moral.
  495.  
  496. Experienced C++ programmers will sometimes redefine a non-virtual fn for
  497. efficiency (the alternate implementation might make better use of the derived
  498. class' resources), or to get around the hiding rule (see below, and ARM
  499. ["Annotated Reference Manual"] sect.13.1).  However the client-visible effects
  500. must be IDENTICAL, since non-virtual fns are dispatched based on the static
  501. type of the ptr/ref rather than the dynamic type of the pointed-to/referenced
  502. object.
  503.  
  504. ==============================================================================
  505.  
  506. Q59: What's the meaning of, "Warning: Derived::f(int) hides Base::f(float)"?
  507.  
  508. It means you're going to die.
  509.  
  510. Here's the mess you're in: if Derived declares a member function named "f", and
  511. Base declares a member function named "f" with a different signature (e.g.,
  512. different parameter types and/or constness), then the Base "f" is "hidden"
  513. rather than "overloaded" or "overridden" (even if the Base "f" is virtual).
  514.  
  515. Here's how you get out of the mess: Derived must redefine the Base member
  516. function(s) that are hidden (even if they are non-virtual).  Normally this
  517. re-definition merely calls the appropriate Base member function.  E.g.,
  518.  
  519.         class Base {
  520.         public:
  521.           void f(int);
  522.         };
  523.  
  524.         class Derived : public Base {
  525.         public:
  526.           void f(double);
  527.           void f(int i) { Base::f(i); }
  528.         };             // ^^^^^^^^^^--- redefinition merely calls Base::f(int)
  529.  
  530. ==============================================================================
  531. SUBSECTION 12B: Inheritance -- Conformance
  532. ==============================================================================
  533.  
  534. Q60: Should I hide public member fns inherited from my base class?
  535.  
  536. Never, never, never do this.  Never.  NEVER!
  537.  
  538. Attempting to hide (eliminate, revoke) inherited public member functions is an
  539. all-too-common design error.  It usually stems from muddy thinking.
  540.  
  541. ==============================================================================
  542.  
  543. Q61: Is a "Circle" a kind-of an "Ellipse"?
  544.  
  545. Not if Ellipse promises to be able to change its size asymmetrically.
  546.  
  547. For example, suppose Ellipse has a "setSize(x,y)" method, and suppose this
  548. method promises "the Ellipse's width() will be x, and its height() will be y".
  549. In this case, Circle can't be a kind-of Ellipse.  Simply put, if Ellipse can do
  550. something Circle can't, then Circle can't be a kind of Ellipse.
  551.  
  552. This leaves two potential (valid) relationships between Circle and Ellipse:
  553.  * Make Circle and Ellipse completely unrelated classes.
  554.  * Derive Circle and Ellipse from a base class representing "Ellipses that
  555.    can't NECESSARILY perform an unequal-setSize operation."
  556.  
  557. In the first case, Ellipse could be derived from class "AsymmetricShape" (with
  558. setSize(x,y) being introduced in AsymmetricShape), and Circle could be derived
  559. from "SymmetricShape," which has a setSize(size) member fn.
  560.  
  561. In the second case, class "Oval" could only have "setSize(size)" which sets
  562. both the "width()" and the "height()" to "size", then derive both Ellipse and
  563. Circle from Oval.  Ellipse --but not Circle-- adds the "setSize(x,y)" operation
  564. (see the "hiding rule" for a caveat if the same method name "setSize()" is used
  565. for both operations).
  566.  
  567. ==============================================================================
  568.  
  569. Q62: Are there other options to the "Circle is/isnot kind-of Ellipse"
  570.    dilemma?
  571.  
  572. If you claim that all Ellipses can be squashed asymmetrically, and you claim
  573. that Circle is a kind-of Ellipse, and you claim that Circle can't be squashed
  574. asymmetrically, clearly you've got to adjust (revoke, actually) one of your
  575. claims.  Thus you've either got to get rid of "Ellipse::setSize(x,y)", get rid
  576. of the inheritance relationship between Circle and Ellipse, or admit that your
  577. "Circle"s aren't necessarily circular.
  578.  
  579. Here are the two most common traps new OO/C++ programmers regularly fall into.
  580. They attempt to use coding hacks to cover up a broken design (they redefine
  581. Circle::setSize(x,y) to throw an exception, call "abort()", or choose the
  582. average of the two parameters, or to be a no-op).  Unfortunately all these
  583. hacks will surprise users, since users are expecting "width() == x" and
  584. "height() == y".
  585.  
  586. The only rational way out of this would be to weaken the promise made by
  587. Ellipse's "setSize(x,y)" (e.g., you'd have to change it to, "This method MIGHT
  588. set width() to x and height() to y, or it might do NOTHING").  Unfortunately
  589. this dilutes the contract into dribble, since the user can't rely on any
  590. meaningful behavior.  The whole hierarchy therefore begins to be worthless
  591. (it's hard to convince someone to use an object if you have to shrug your
  592. shoulders when asked what the object does for them).
  593.  
  594. ==============================================================================
  595. SUBSECTION 12C: Inheritance -- Access rules
  596. ==============================================================================
  597.  
  598. Q63: Why can't my derived class access "private" things from my base class?
  599.  
  600. To protect you from future changes to the base class.
  601.  
  602. Derived classes do not get access to private members of a base class.  This
  603. effectively "seals off" the derived class from any changes made to the private
  604. members of the base class.
  605.  
  606. ==============================================================================
  607.  
  608. Q64: What's the difference between "public:", "private:", and "protected:"?
  609.  
  610. "Private:" is discussed in the previous section, and "public:" means "anyone
  611. can access it."  The third option, "protected:", makes a member (either data
  612. member or member fn) accessible to subclasses.
  613.  
  614. ==============================================================================
  615.  
  616. Q65: How can I protect subclasses from breaking when I change internal parts?
  617.  
  618. A class has two distinct interfaces for two distinct sets of clients:
  619.  * its "public:" interface serves unrelated classes.
  620.  * its "protected:" interface serves derived classes.
  621.  
  622. Unless you expect all your subclasses to be built by your own team, you should
  623. consider making your base class's bits be "private:", and use "protected:"
  624. inline access functions to access these data.  This way the private bits can
  625. change, but the derived class's code won't break unless you change the
  626. protected access functions.
  627.  
  628. ==============================================================================
  629. SUBSECTION 12D: Inheritance -- Constructors and destructors
  630. ==============================================================================
  631.  
  632. Q66: When my base class's constructor calls a virtual function, why doesn't my
  633.    derived class's override of that virtual function get invoked?
  634.  
  635. During the Base class's constructor, the object isn't yet a Derived, so if
  636. "Base::Base()" calls a virtual function "virt()", the "Base::virt()" will be
  637. invoked, even if "Derived::virt()" exists.
  638.  
  639. Similarly, during Base's destructor, the object is no longer a Derived, so when
  640. Base::~Base() calls "virt()", "Base::virt()" gets control, NOT the
  641. "Derived::virt()" override.
  642.  
  643. You'll quickly see the wisdom of this approach when you imagine the disaster if
  644. "Derived::virt()" touched a member object from the Derived class.
  645.  
  646. ==============================================================================
  647.  
  648. Q67: Does a derived class destructor need to explicitly call the base
  649.    destructor?
  650.  
  651. No, never explicitly call a destructor (where "never" means "rarely").
  652.  
  653. A derived class's destructor (whether or not you explicitly define one)
  654. AUTOMATICALLY invokes the destructors for member objects and base class
  655. subobjects.  Member objects are destroyed in the reverse order they appear
  656. within the class, then base class subobjects are destroyed in the reverse order
  657. that they appear in the class's list of base classes.
  658.  
  659. You should explicitly call a destructor ONLY in esoteric situations, such as
  660. when destroying an object created by the "placement new operator."
  661.  
  662. ==============================================================================
  663. SUBSECTION 12E: Inheritance -- Private and protected inheritance
  664. ==============================================================================
  665.  
  666. Q68: How do you express "private inheritance"?
  667.  
  668. When you use ": private" instead of ": public."  E.g.,
  669.  
  670.         class Foo : private Bar {
  671.           //...
  672.         };
  673.  
  674. ==============================================================================
  675.  
  676. Q69: How are "private inheritance" and "composition" similar?
  677.  
  678. Private inheritance is a syntactic variant of composition (has-a).
  679.  
  680. E.g., the "car has-a engine" relationship can be expressed using composition:
  681.  
  682.         class Engine {
  683.         public:
  684.           Engine(int numCylinders);
  685.           void start();                 //starts this Engine
  686.         };
  687.  
  688.         class Car {
  689.         public:
  690.           Car() : e_(8) { }             //initializes this Car with 8 cylinders
  691.           void start() { e_.start(); }  //start this Car by starting its engine
  692.         private:
  693.           Engine e_;
  694.         };
  695.  
  696. The same "has-a" relationship can also be expressed using private inheritance:
  697.  
  698.         class Car : private Engine {
  699.         public:
  700.           Car() : Engine(8) { }         //initializes this Car with 8 cylinders
  701.           Engine::start;                //start this Car by starting its engine
  702.         };
  703.  
  704. There are several similarities between these two forms of composition:
  705.  * in both cases there is exactly one Engine member object contained in a Car.
  706.  * in neither case can users (outsiders) convert a Car* to an Engine*.
  707.  
  708. There are also several distinctions:
  709.  * the first form is needed if you want to contain several Engines per Car.
  710.  * the second form can introduce unnecessary multiple inheritance.
  711.  * the second form allows members of Car to convert a Car* to an Engine*.
  712.  * the second form allows access to the "protected" members of the base class.
  713.  * the second form allows Car to override Engine's virtual functions.
  714.  
  715. Note that private inheritance is usually used to gain access into the
  716. "protected:" members of the base class, but this is usually a short-term
  717. solution (translation: a band-aid; see below).
  718.  
  719. ==============================================================================
  720.  
  721. Q70: Which should I prefer: composition or private inheritance?
  722.  
  723. Composition.
  724.  
  725. Normally you don't WANT to have access to the internals of too many other
  726. classes, and private inheritance gives you some of this extra power (and
  727. responsibility).  But private inheritance isn't evil; it's just more expensive
  728. to maintain, since it increases the probability that someone will change
  729. something that will break your code.
  730.  
  731. A legitimate, long-term use for private inheritance is when you want to build a
  732. class Fred that uses code in a class Wilma, and the code from class Wilma needs
  733. to invoke methods from your new class, Fred.  In this case, Fred calls
  734. non-virtuals in Wilma, and Wilma calls (usually pure) virtuals in itself, which
  735. are overridden by Fred.  This would be much harder to do with composition.
  736.  
  737.         class Wilma {
  738.         protected:
  739.           void fredCallsWilma()
  740.             { cout << "Wilma::fredCallsWilma()\n"; wilmaCallsFred(); }
  741.           virtual void wilmaCallsFred() = 0;
  742.         };
  743.  
  744.         class Fred : private Wilma {
  745.         public:
  746.           void barney()
  747.             { cout << "Fred::barney()\n"; Wilma::fredCallsWilma(); }
  748.         protected:
  749.           virtual void wilmaCallsFred()
  750.             { cout << "Fred::wilmaCallsFred()\n"; }
  751.         };
  752.  
  753. ==============================================================================
  754.  
  755. Q71: Should I pointer-cast from a "privately" derived class to its base
  756.    class?
  757.  
  758. Generally, No.
  759.  
  760. From a method or friend of a privately derived class, the relationship to the
  761. base class is known, and the upward conversion from PrivatelyDer* to Base* (or
  762. PrivatelyDer& to Base&) is safe; no cast is needed or recommended.
  763.  
  764. However users of PrivateDer should avoid this unsafe conversion, since it is
  765. based on a "private" decision of PrivateDer, and is subject to change without
  766. notice.
  767.  
  768. ==============================================================================
  769.  
  770. Q72: How is protected inheritance related to private inheritance?
  771.  
  772. Similarities: both allow overriding virtuals in the private/protected base
  773. class, neither claims the derived is a kind-of its base.
  774.  
  775. Dissimilarities: protected inheritance allows derived classes of derived
  776. classes to know about the inheritance relationship (it exposes your grand kids
  777. to your implementation details).  This has both benefits (it allows subclasses
  778. of the protected derived class to exploit the relationship to the protected
  779. base class) and costs (the protected derived class can't change the
  780. relationship without potentially breaking further derived classes).
  781.  
  782. Protected inheritance uses the ": protected" syntax:
  783.  
  784.         class Car : protected Engine {
  785.           //...
  786.         };
  787.  
  788. ==============================================================================
  789.  
  790. Q73: What are the access rules with "private" and "protected" inheritance?
  791.  
  792. Take these classes as examples:
  793.  
  794.         class B                    { /*...*/ };
  795.         class D_priv : private   B { /*...*/ };
  796.         class D_prot : protected B { /*...*/ };
  797.         class D_publ : public    B { /*...*/ };
  798.         class UserClass            { B b; /*...*/ };
  799.  
  800. None of the subclasses can access anything that is private in B.  In D_priv,
  801. the public and protected parts of B are "private".  In D_prot, the public and
  802. protected parts of B are "protected".  In D_publ, the public parts of B are
  803. public and the protected parts of B are protected (D_publ is-a-kind-of-a B).
  804. Class "UserClass" can access only the public parts of B, which "seals off"
  805. UserClass from B.
  806.  
  807. To make a public member of B so it is public in D_priv or D_prot, state the
  808. name of the member with a "B::" prefix.  E.g., to make member "B::f(int,float)"
  809. public in D_prot, you would say:
  810.  
  811.         class D_prot : protected B {
  812.         public:
  813.           B::f;    //note: not  "B::f(int,float)"
  814.         };
  815.  
  816. ==============================================================================
  817. SECTION 13: Abstraction
  818. ==============================================================================
  819.  
  820. Q74: What's the big deal of separating interface from implementation?
  821.  
  822. Interfaces are a company's most valuable resources.  Designing an interface
  823. takes longer than whipping together a concrete class which fulfills that
  824. interface.  Furthermore interfaces require the time of more expensive people.
  825.  
  826. Since interfaces are so valuable, they should be protected from being tarnished
  827. by data structures and other implementation artifacts.  Thus you should
  828. separate interface from implementation.
  829.  
  830. ==============================================================================
  831.  
  832. Q75: How do I separate interface from implementation in C++ (like Modula-2)?
  833.  
  834. Use an ABC (see next FAQ).
  835.  
  836. ==============================================================================
  837.  
  838. Q76: What is an ABC ("abstract base class")?
  839.  
  840. At the design level, an ABC corresponds to an abstract concept.  If you asked a
  841. Mechanic if he repaired Vehicles, he'd probably wonder what KIND-OF Vehicle you
  842. had in mind.  Chances are he doesn't repair space shuttles, ocean liners,
  843. bicycles, or nuclear submarines.  The problem is that the term "Vehicle" is an
  844. abstract concept (e.g., you can't build a "vehicle" unless you know what kind
  845. of vehicle to build).  In C++, class Vehicle would be an ABC, with Bicycle,
  846. SpaceShuttle, etc, being subclasses (an OceanLiner is-a-kind-of-a Vehicle).  In
  847. real-world OOP, ABCs show up all over the place.
  848.  
  849. As programming language level, an ABC is a class that has one or more pure
  850. virtual member functions (see next FAQ).  You cannot make an object (instance)
  851. of an ABC.
  852.  
  853. ==============================================================================
  854.  
  855. Q77: What is a "pure virtual" member function?
  856.  
  857. A member function of an ABC that you can implement only in a derived class.
  858.  
  859. Some member functions exist in concept, but can't have any actual defn.  E.g.,
  860. suppose I asked you to draw a Shape at location (x,y) that has size 7.  You'd
  861. ask me "what kind of shape should I draw?" (circles, squares, hexagons, etc,
  862. are drawn differently).  In C++, we indicate the existence of the "draw()"
  863. method, but we recognize it can (logically) be defined only in subclasses:
  864.  
  865.         class Shape {
  866.         public:
  867.           virtual void draw() const = 0;
  868.           //...                     ^^^--- "= 0" means it is "pure virtual"
  869.         };
  870.  
  871. This pure virtual function makes "Shape" an ABC.  If you want, you can think of
  872. the "= 0" syntax as if the code were at the NULL pointer.  Thus "Shape"
  873. promises a service to its users, yet Shape isn't able to provide any code to
  874. fulfill that promise.  This ensures any actual object created from a [concrete]
  875. class derived of Shape *WILL* have the indicated member fn, even though the
  876. base class doesn't have enough information to actually DEFINE it yet.
  877.  
  878. ==============================================================================
  879.  
  880. Q78: How can I provide printing for an entire hierarchy of classes?
  881.  
  882. Provide a friend operator<< that calls a protected virtual function:
  883.  
  884.         class Base {
  885.         public:
  886.           friend ostream& operator<< (ostream& o, const Base& b)
  887.             { b.print(o); return o; }
  888.           //...
  889.         protected:
  890.           virtual void print(ostream& o) const;  //or "=0;" if "Base" is an ABC
  891.         };
  892.  
  893.         class Derived : public Base {
  894.         protected:
  895.           virtual void print(ostream& o) const;
  896.         };
  897.  
  898. Now all subclasses of Base merely provide their own "print(ostream&) const"
  899. member function (they all share the common "<<" operator).  This technique
  900. allows friends to ACT as if they supported dynamic binding.
  901.  
  902. ==============================================================================
  903.  
  904. Q79: When should my destructor be virtual?
  905.  
  906. When you may "delete" a derived object via a base pointer.
  907.  
  908. Virtual fns bind to the code associated with the class of the object, rather
  909. than with the class of the pointer/ref.  When you say "delete basePtr", and the
  910. base class has a virtual destructor, the destructor that gets invoked is the
  911. one associated with the type of the object *basePtr, rather than the one
  912. associated with the type of the pointer.  This is generally A Good Thing.
  913.  
  914. To make life easy for you, the only time you wouldn't want to make a class's
  915. destructor virtual is if that class has NO virtual fns, since the introduction
  916. of the first virtual fn imposes some space overhead in each object (typically
  917. one machine word).  This is how the compiler implements the magic of dynamic
  918. binding; it usually boils down to an extra ptr per object called the "virtual
  919. table pointer" or "vptr".
  920.  
  921. ==============================================================================
  922.  
  923. Q80: What is a "virtual constructor"?
  924.  
  925. An idiom that allows you to do something that C++ doesn't directly support.
  926.  
  927. You can get the effect of virtual constructor by a virtual "createCopy()"
  928. member fn (for copy constructing), or a virtual "createSimilar()" member fn
  929. (for the default constructor).
  930.  
  931.         class Shape {
  932.         public:
  933.           virtual ~Shape() { }          //see on "virtual destructors" for more
  934.           virtual void draw() = 0;
  935.           virtual void move() = 0;
  936.           //...
  937.           virtual Shape* createCopy() const = 0;
  938.           virtual Shape* createSimilar() const = 0;
  939.         };
  940.  
  941.         class Circle : public Shape {
  942.         public:
  943.           Circle* createCopy()    const { return new Circle(*this); }
  944.           Circle* createSimilar() const { return new Circle(); }
  945.           //...
  946.         };
  947.  
  948. The invocation of "Circle(*this)" is that of copy construction ("*this" has
  949. type "const Circle&" in these methods).  "createSimilar()" is similar, but it
  950. constructs a "default" Circle.
  951.  
  952. Users use these as if they were "virtual constructors":
  953.  
  954.         void userCode(Shape& s)
  955.         {
  956.           Shape* s2 = s.createCopy();
  957.           Shape* s3 = s.createSimilar();
  958.           //...
  959.           delete s2;    //relies on destructor being virtual!!
  960.           delete s3;    // ditto
  961.         }
  962.  
  963. This fn will work correctly regardless of whether the Shape is a Circle,
  964. Square, or some other kind-of Shape that doesn't even exist yet.
  965.  
  966. --
  967. Paradigm Shift, Inc. / P.O. Box 5108 / Potsdam, NY  13676
  968. Technology consulting services
  969. cline@parashift.com / Voice: 315-353-6100 / FAX: 315-353-6110
  970.  
  971.  
  972.